package com.ccc.javacv.convertor.ffmpeg;

import com.ccc.javacv.pojo.ConvertContext;
import com.ccc.javacv.pojo.TaskContext;
import com.ccc.javacv.convertor.VideoConvertor;
import com.ccc.javacv.convertor.VideoConvertorTask;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.Loader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Set;

/***
 * 视频流转换器实现——FFmpeg
 */
@Service
@Slf4j
public class FfmpegVideoConvertor implements VideoConvertor {

    /**
     * 支持的协议
     */
    @Value("${vediojc.javacv.protocols.support:rtsp,rtmp,http}")
    private Set<String> supportProtocols;
    /**
     * 支持的目标格式
     */
    @Value("${vediojc.javacv.target-formats.support:flv}")
    private Set<String> supportTargetFormats;

    /**
     * 是否进行日志跟踪
     */
    @Value("${vediojs.process.monitor.trace-log:false}")
    private boolean traceLog;

    /**
     * 线程池
     */
    @Autowired
    @Qualifier("processMonitorTaskPool")
    private ThreadPoolTaskExecutor processMonitorTaskPool;

    private String ffmpegPath;

    @PostConstruct
    public void init() {
        log.info("[ffmpeg]正在初始化资源，请稍等...");
        ffmpegPath = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
    }

    @Override
    public boolean isSupport(ConvertContext convertContext) {
        return supportProtocols.contains(convertContext.getSourceProtocol())
                && supportTargetFormats.contains(convertContext.getVideoInfo().getTargetFormat())
                && convertContext.getVideoInfo().getFfmpeg()
                ;
    }

    @Override
    public Integer priority() {
        // 优先级
        return 100;
    }

    /**
     * 准备转换
     *
     * @param convertContext 上下文
     */
    @Override
    public VideoConvertorTask prepareConvert(ConvertContext convertContext) {
        FfmpegVideoConvertorTask ffmpegVideoConvertorTask;
        TaskContext taskContext = new TaskContext();
        taskContext.setId(convertContext.getTaskId());
        taskContext.setNotAutoClose(Boolean.FALSE.equals(convertContext.getAutoClose()));
        taskContext.setVideoInfo(convertContext.getVideoInfo());
        taskContext.setSourceProtocol(convertContext.getSourceProtocol());
        ffmpegVideoConvertorTask = new FfmpegVideoConvertorTask(taskContext, ffmpegPath, processMonitorTaskPool);
        ffmpegVideoConvertorTask.setTraceLog(traceLog);
        return ffmpegVideoConvertorTask;
    }
}
